<template>
  <div class="sync-container">
    <el-card class="sync-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">订单同步管理</span>
          <div class="card-actions">
            <el-button type="info" @click="testConnection" :loading="testing">
              测试连接
            </el-button>
            <el-button type="primary" @click="startSync" :loading="syncing">
              开始同步
            </el-button>
          </div>
        </div>
      </template>

      <!-- 同步状态 -->
      <div class="status-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="status-card">
              <div class="status-item">
                <div class="status-number">{{ status.total_orders || 0 }}</div>
                <div class="status-label">总订单数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="status-card">
              <div class="status-item">
                <div class="status-number">{{ status.today_orders || 0 }}</div>
                <div class="status-label">今日订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="status-card">
              <div class="status-item">
                <div class="status-number">{{ status.week_orders || 0 }}</div>
                <div class="status-label">本周订单</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="status-card">
              <div class="status-item">
                <div class="status-number">{{ lastSyncDate }}</div>
                <div class="status-label">最后同步</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 同步配置 -->
      <div class="config-section">
        <el-form :model="syncForm" label-width="120px" class="sync-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始日期">
                <el-date-picker
                  v-model="syncForm.start_date"
                  type="date"
                  placeholder="选择开始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期">
                <el-date-picker
                  v-model="syncForm.end_date"
                  type="date"
                  placeholder="选择结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最大同步天数">
                <el-input-number
                  v-model="syncForm.max_days"
                  :min="1"
                  :max="365"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="批次大小">
                <el-input-number
                  v-model="syncForm.batch_size"
                  :min="10"
                  :max="1000"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 同步结果 -->
      <div v-if="syncResult" class="result-section">
        <el-card shadow="hover">
          <template #header>
            <span>同步结果</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="同步订单数">
              <el-tag type="success">{{ syncResult.total_synced }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="跳过订单数">
              <el-tag type="info">{{ syncResult.total_skipped }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="重复订单数">
              <el-tag type="warning">{{ syncResult.duplicate_count }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="错误数量">
              <el-tag type="danger">{{ syncResult.error_count }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="同步日期范围" :span="2">
              {{ syncResult.sync_date_range.start_date }} 至 {{ syncResult.sync_date_range.actual_end_date }}
            </el-descriptions-item>
          </el-descriptions>
          
          <!-- 错误信息 -->
          <div v-if="syncResult.errors && syncResult.errors.length > 0" class="error-section">
            <h4>错误信息：</h4>
            <el-alert
              v-for="(error, index) in syncResult.errors"
              :key="index"
              :title="error"
              type="error"
              show-icon
              :closable="false"
              style="margin-bottom: 10px"
            />
          </div>
        </el-card>
      </div>

      <!-- 连接测试结果 -->
      <div v-if="connectionResult" class="connection-section">
        <el-card shadow="hover">
          <template #header>
            <span>连接测试结果</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="连接状态">
              <el-tag :type="connectionResult.connection_status === 'success' ? 'success' : 'danger'">
                {{ connectionResult.connection_status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="测试日期">
              {{ connectionResult.test_date }}
            </el-descriptions-item>
            <el-descriptions-item label="订单数量">
              {{ connectionResult.orders_count }}
            </el-descriptions-item>
            <el-descriptions-item label="API响应">
              {{ connectionResult.api_response }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApi } from '@/composables/useApi'
import * as dayjs from 'dayjs'

const api = useApi()

// 数据
const syncing = ref(false)
const testing = ref(false)
const status = ref({})
const syncResult = ref(null)
const connectionResult = ref(null)

// 同步表单
const syncForm = reactive({
  start_date: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
  end_date: dayjs().format('YYYY-MM-DD'),
  max_days: 365,
  batch_size: 100
})

// 计算属性
const lastSyncDate = computed(() => {
  if (status.value.last_sync_date) {
    return dayjs(status.value.last_sync_date).format('YYYY-MM-DD HH:mm:ss')
  }
  return '未同步'
})

// 加载同步状态
const loadStatus = async () => {
  try {
    const response = await api.get('/orders/sync/status')
    if (response.code === 200) {
      status.value = response.data
    } else {
      ElMessage.error(response.message || '获取同步状态失败')
    }
  } catch (error) {
    console.error('获取同步状态失败:', error)
    ElMessage.error('获取同步状态失败')
  }
}

// 测试连接
const testConnection = async () => {
  try {
    testing.value = true
    const response = await api.get('/orders/sync/test')
    
    if (response.code === 200) {
      connectionResult.value = response.data
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error(response.message || '连接测试失败')
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

// 开始同步
const startSync = async () => {
  try {
    // 确认同步
    await ElMessageBox.confirm(
      `确定要开始同步订单数据吗？\n同步范围：${syncForm.start_date} 至 ${syncForm.end_date}\n最大同步天数：${syncForm.max_days}天`,
      '确认同步',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    syncing.value = true
    const response = await api.post('/orders/sync', syncForm)
    
    if (response.code === 200) {
      syncResult.value = response.data
      ElMessage.success('订单同步完成')
      // 重新加载状态
      await loadStatus()
    } else {
      ElMessage.error(response.message || '同步失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('同步失败:', error)
      ElMessage.error('同步失败')
    }
  } finally {
    syncing.value = false
  }
}

// 页面加载
onMounted(() => {
  loadStatus()
})
</script>

<style scoped>
.sync-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.sync-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.status-section {
  margin-bottom: 20px;
}

.status-card {
  text-align: center;
}

.status-item {
  padding: 10px;
}

.status-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.status-label {
  font-size: 14px;
  color: #909399;
}

.config-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
}

.sync-form {
  max-width: 800px;
}

.result-section,
.connection-section {
  margin-top: 20px;
}

.error-section {
  margin-top: 15px;
}

.error-section h4 {
  margin: 0 0 10px 0;
  color: #f56c6c;
}
</style> 